const express = require('express');
const router = express.Router();
const authMiddleware = require('../middlewares/auth.middleware');
const audioUpload = require('../middlewares/audioUpload.middleware');
const pronunciationController = require('../controllers/pronunciationController');
const mysql = require('../config/db.config');

// 所有路由都需要认证
router.use(authMiddleware);

// 发音评估路由
router.post('/assess/scripted', audioUpload.single('audio'), pronunciationController.assessScripted);

// 获取评估详情
router.get('/assessment/:assessmentId/details', async (req, res) => {
    try {
        const userId = req.user?.userId || req.user?.id;
        const { assessmentId } = req.params;

        if (!userId) {
            return res.status(400).json({
                success: false,
                message: 'User ID not found'
            });
        }

        // 1. 获取评估基本信息
        const [[assessment]] = await mysql.query(
            `SELECT 
                assessment_id,
                assessment_type,
                reference_text,
                status,
                pronunciation_score,
                accuracy_score,
                fluency_score,
                prosody_score,
                completeness_score,
                recognized_text,
                audio_url,
                created_at,
                updated_at
            FROM pronunciation_assessments 
            WHERE assessment_id = ? AND user_id = ? AND is_delete = 0`,
            [assessmentId, userId]
        );

        if (!assessment) {
            return res.status(404).json({
                success: false,
                message: '评估记录不存在或无权限访问'
            });
        }

        // 2. 获取单词级别的详细评估信息
        const [details] = await mysql.query(
            `SELECT 
                word,
                word_accuracy_score,
                word_error_type,
                syllables,
                phonemes,
                offset_ms,
                duration_ms,
                prosody_feedback
            FROM pronunciation_assessment_details 
            WHERE assessment_id = ? 
            ORDER BY offset_ms ASC`,
            [assessmentId]
        );

        // 3. 处理返回数据
        const baseUrl = `${req.protocol}://${req.get('host')}`;
        const response = {
            success: true,
            data: {
                assessment: {
                    assessmentId: assessment.assessment_id,
                    type: assessment.assessment_type,
                    referenceText: assessment.reference_text,
                    status: assessment.status,
                    scores: assessment.status === 'completed' ? {
                        pronunciation: Number(assessment.pronunciation_score || 0).toFixed(2),
                        accuracy: Number(assessment.accuracy_score || 0).toFixed(2),
                        fluency: Number(assessment.fluency_score || 0).toFixed(2),
                        prosody: Number(assessment.prosody_score || 0).toFixed(2),
                        completeness: Number(assessment.completeness_score || 0).toFixed(2)
                    } : null,
                    recognizedText: assessment.recognized_text,
                    audioUrl: assessment.audio_url ? `${baseUrl}${assessment.audio_url}` : null,
                    createdAt: assessment.created_at,
                    updatedAt: assessment.updated_at
                },
                details: details.map(detail => {
                    // 安全的 JSON 解析函数
                    const safeJSONParse = (data, defaultValue = []) => {
                        if (!data) return defaultValue;
                        if (typeof data === 'object') return data;
                        try {
                            return JSON.parse(data);
                        } catch (e) {
                            // 只在开发环境输出错误
                            if (process.env.NODE_ENV === 'development') {
                                console.error('JSON parse error:', e);
                            }
                            return defaultValue;
                        }
                    };

                    return {
                        word: detail.word,
                        accuracyScore: Number(detail.word_accuracy_score || 0).toFixed(2),
                        errorType: detail.word_error_type,
                        timing: {
                            offset: detail.offset_ms,
                            duration: detail.duration_ms
                        },
                        syllables: safeJSONParse(detail.syllables, []).map(syllable => ({
                            text: syllable.Syllable,
                            accuracyScore: syllable.PronunciationAssessment?.AccuracyScore,
                            timing: {
                                offset: syllable.Offset,
                                duration: syllable.Duration
                            }
                        })),
                        phonemes: safeJSONParse(detail.phonemes, []).map(phoneme => ({
                            text: phoneme.Phoneme,
                            accuracyScore: phoneme.PronunciationAssessment?.AccuracyScore,
                            timing: {
                                offset: phoneme.Offset,
                                duration: phoneme.Duration
                            },
                            alternatives: phoneme.PronunciationAssessment?.NBestPhonemes?.map(alt => ({
                                phoneme: alt.Phoneme,
                                score: alt.Score
                            })) || []
                        })),
                        prosody: {
                            break: safeJSONParse(detail.prosody_feedback, {})?.Prosody?.Break || {
                                errorTypes: [],
                                breakLength: 0
                            },
                            intonation: safeJSONParse(detail.prosody_feedback, {})?.Prosody?.Intonation || {
                                errorTypes: [],
                                monotone: {
                                    syllablePitchDeltaConfidence: 0
                                }
                            }
                        }
                    };
                })
            }
        };

        return res.json(response);

    } catch (error) {
        console.error('Error fetching assessment details:', error);
        return res.status(500).json({
            success: false,
            message: '获取评估详情失败: ' + error.message
        });
    }
});

// 获取用户的评估历史记录
router.get('/history', async (req, res) => {
    try {
        // 从认证中间件获取用户ID
        const userId = req.user?.userId || req.user?.id;
        if (!userId) {
            return res.status(400).json({
                success: false,
                message: 'User ID not found'
            });
        }
        
        const [assessments] = await mysql.query(
            `SELECT 
                assessment_id,
                assessment_type,
                reference_text,
                status,
                pronunciation_score,
                accuracy_score,
                fluency_score,
                prosody_score,
                completeness_score,
                recognized_text,
                audio_url,
                tts_audio_url,
                created_at,
                updated_at
             FROM pronunciation_assessments 
             WHERE user_id = ? AND is_delete = 0
             ORDER BY created_at DESC`,
            [userId]
        );

        // 处理返回数据，确保音频URL是完整的
        const baseUrl = `${req.protocol}://${req.get('host')}`;
        return res.json({
            success: true,
            data: assessments.map(assessment => ({
                assessmentId: assessment.assessment_id,
                type: assessment.assessment_type,
                referenceText: assessment.reference_text,
                status: assessment.status,
                scores: assessment.assessment_type === 'scripted' && assessment.status === 'completed' ? {
                    pronunciation: Number(assessment.pronunciation_score || 0).toFixed(2),
                    accuracy: Number(assessment.accuracy_score || 0).toFixed(2),
                    fluency: Number(assessment.fluency_score || 0).toFixed(2),
                    prosody: Number(assessment.prosody_score || 0).toFixed(2),
                    completeness: Number(assessment.completeness_score || 0).toFixed(2)
                } : null,
                recognizedText: assessment.recognized_text,
                audioUrl: assessment.audio_url ? `${baseUrl}${assessment.audio_url}` : null,
                ttsAudioUrl: assessment.tts_audio_url ? `${baseUrl}${assessment.tts_audio_url}` : null,
                createdAt: assessment.created_at,
                updatedAt: assessment.updated_at
            }))
        });
    } catch (error) {
        console.error('Error fetching assessment history:', error);
        return res.status(500).json({
            success: false,
            message: '获取评估历史失败: ' + error.message
        });
    }
});

// 删除评估记录（软删除）
router.delete('/assessment/:assessmentId', async (req, res) => {
    try {
        const userId = req.user?.userId || req.user?.id;
        const { assessmentId } = req.params;

        if (!userId) {
            return res.status(400).json({
                success: false,
                message: 'User ID not found'
            });
        }

        // 检查记录是否存在且属于当前用户
        const [[assessment]] = await mysql.query(
            'SELECT assessment_id FROM pronunciation_assessments WHERE assessment_id = ? AND user_id = ? AND is_delete = 0',
            [assessmentId, userId]
        );

        if (!assessment) {
            return res.status(404).json({
                success: false,
                message: '评估记录不存在或无权限删除'
            });
        }

        // 执行软删除
        await mysql.query(
            'UPDATE pronunciation_assessments SET is_delete = 1, updated_at = NOW() WHERE assessment_id = ?',
            [assessmentId]
        );

        return res.json({
            success: true,
            message: '删除成功'
        });

    } catch (error) {
        console.error('Error deleting assessment:', error);
        return res.status(500).json({
            success: false,
            message: '删除失败: ' + error.message
        });
    }
});

module.exports = router; 